package com.sl.gateway.filter;

import cn.hutool.core.convert.Convert;
import com.itheima.auth.sdk.dto.AuthUserInfoDTO;
import com.sl.gateway.config.MyConfig;
import com.sl.transport.common.constant.Constants;
import com.sl.transport.common.util.JwtUtils;
import com.sl.transport.common.util.ObjectUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 管理app用户端校验的拦截器
 */
@Component
public class CustomerTokenGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> implements AuthFilter {

    @Resource
    private MyConfig myConfig;

    @Value("${sl.jwt.public-key}")
    private String publicKeyStr;

    @Override
    public GatewayFilter apply(Object config) {
        return new TokenGatewayFilter(this,this.myConfig);
    }

    @Override
    public AuthUserInfoDTO check(String token) {
        //调用工具类中方法进行校验
        Map<String, Object> checkToken = JwtUtils.checkToken(token, publicKeyStr);
        if (ObjectUtil.isEmpty(checkToken)) {
            return null;
        }
        //其中只存储了userId
        Long userId = Convert.toLong(checkToken.get(Constants.GATEWAY.USER_ID));
        //构建返回对象
        AuthUserInfoDTO authUserInfoDTO = new AuthUserInfoDTO();
        authUserInfoDTO.setUserId(userId);
        return authUserInfoDTO;
    }

    @Override
    public Boolean auth(String token, AuthUserInfoDTO authUserInfo, String path) {
        //没有权限验证
        return true;
    }

    @Override
    public String tokenHeaderName() {
        return Constants.GATEWAY.ACCESS_TOKEN;
    }
}
